import { observable, action } from 'mobx';
import { WeaForm } from 'comsMobx';
import * as API from '../apis/mobileSetting';
import { Modal, message } from "antd";
import { WeaLocaleProvider } from "ecCom";

const getLabel = WeaLocaleProvider.getLabel;

export default class Store {

    baseParams = {};
    fields = {};//非流程中心condition
    newflowFields = {};//流程中心新建流程-流程来源弹框condition

    //流程中心--weatable属性
    contentdatas = [];//流程中心内容设置数据信息
    contentcolumns = [];//流程中心内容设置列信息
    @observable operatedatas = [];//流程中心操作菜单设置数据信息
    operatecolumns = [];//流程中心操作菜单设置列信息
    @observable selectedOperate = { enable: [] };//流程中心--操作菜单设置--启用已勾选数据

    //流程中心--内容设置--form相关
    contentSettingFields = {};//流程中心-内容设置condition
    viewtypeFields = {}//流程中心-内容设置condition中--查看类型辅助项condition
    orderColDatas = [];//流程中心--排序字段选择框数据
    orderColDatasMap = [];//流程中心--排序字段临时数据map
    @observable selectedOrders = [];//流程中心--排序字段选择框--已选数据

    //form相关
    @observable form = null;//普通form
    @observable newflowForm = null;//流程中心--操作菜单--新建流程中流程来源form
    @observable contentSettingForm = null;//--流程中心--内容设置form

    callBackEvent = null;
    @observable isWfcenterApp = null;
    resetSelectKeys = false;

    currentTabid = -1;
    @observable wfContentLoading = true;
    /**
     * 控制各种小菜单的显示和隐藏
     */
    @observable showDialog = {
        contentSetting: false,
        newflow: false,
        orderCol: false
    }

    constructor() {
        this.setBaseParams = this.setBaseParams;
        this.doInit = this.doInit;
        this.setDialogShow = this.setDialogShow;
        this.doSaveMobilecenterConfig = this.doSaveMobilecenterConfig;
        this.doDelMobilecenterConfig = this.doDelMobilecenterConfig;
    }

    @action
    setBaseParams = (params = {}) =>  {
        this.baseParams = params;
    }

    doInit = () =>  {
        API.getConfig(this.baseParams).then(data => {
            const { fields, formValue, isWfcenterApp } = data;
            let { contentcolumns, operatecolumns, contentdatas, operatedatas } = data;
            this.isWfcenterApp = isWfcenterApp;
            if (this.isWfcenterApp == "1") {
                this.contentcolumns = contentcolumns.map(o => {
                    if (o.key == 'operate') {
                        o.render = (operate, odata, i) => {
                            //内容设置--设置按钮
                            return <div><span title={getLabel(30747, "设置")}><a onClick={() => {
                                this.wfContentLoading = true;
                                this.setDialogShow('contentSetting', true, {tabid:odata.tabid})
                            }} >{getLabel(30747, "设置")}</a></span>&nbsp;&nbsp;&nbsp;&nbsp;
                                <span title={getLabel(350, "另存为")}><a onClick={() => {
                                    this.wfContentLoading = true;
                                    this.setDialogShow('contentSetting', true, {tabid:odata.tabid,saveAs:true})
                                }}>{getLabel(350, "另存为")}</a></span></div>
                        }
                    }
                    return o;
                });
                this.operatecolumns = operatecolumns.map(o => {
                    if (o.key == 'operate') {
                        o.render = (operate, odata, i) => {
                            if (operate) {
                                //新建流程--流程来源
                                return <div title={operate}><a onClick={() => this.setDialogShow('newflow', true, {tabid:odata.tabid})} >{operate}</a></div>
                            }
                        }
                    }
                    return o;
                });
                if (operatedatas) {
                    operatedatas.map((data, i) => {
                        if (data.enable == '1') {
                            this.selectedOperate.enable.push(i);
                        }
                    });
                }
            }
            this.contentdatas = contentdatas;
            this.operatedatas = operatedatas;
            this.fields = fields;
            this.form = new WeaForm();
            this.form.initFormFieldObj(fields);
            this.form.updateFields(formValue);
        });
    }

    doSave = (callbackEvent) =>  {
        const formValue = this.form && this.form.getFormParams();
        const haveSetting = !(formValue && formValue.sourcetype == 0);
        API.doSaveConfig({ ...this.baseParams, ...formValue, contentdatas: JSON.stringify(this.contentdatas), operatedatas: JSON.stringify(this.operatedatas), isWfcenterApp: this.isWfcenterApp }).then(data => {
            if (data.flag === "success" && typeof callbackEvent === "function")
                callbackEvent(haveSetting);
        });
    }

    /**
     *
     * @param {流程中心内容设置-新建流程操作菜单-新建流程保存}
     */
    @action
    doSaveMobilecenterConfig = (params = {}) =>  {
        if (params.type == "newflow") {
            this.newflowForm.validateForm().then(f => {//操作菜单新建流程按钮--流程来源保存
                let data = this.newflowForm.getFormParams();
                if (data.sourcetype === "0" || f.isValid) {
                    const formValue = this.newflowForm && this.newflowForm.getFormParams();
                    API.doSaveMobileCenterConfig({ ...this.baseParams, ...params, ...formValue, type: "newflow" }).then(data => {
                        if (data.flag === "success") {
                            message.success(getLabel('83551', '保存成功'));
                        } else {
                            message.error(getLabel('22620', "保存失败！"));
                        }
                        this.showDialog.newflow = false;
                    });
                } else {
                    f.showErrors();
                }
            });
        } else if (params.type == "contentSetting") {
            this.contentSettingForm.validateForm().then(f => {//内容设置--具体tab数据保存
                let data = this.contentSettingForm.getFormParams();
                if ((data.title != "" && (data.sourcetype === "0" || ((data.sourcetype == "1" || data.sourcetype == "2") && data.workflowids != '') || ((data.sourcetype == "3" || data.sourcetype == "4") && data.workflowtypes != ''))) || f.isValid) {
                    const formValue = this.contentSettingForm && this.contentSettingForm.getFormParams();
                    let orderColKeys = '';
                    this.selectedOrders.length > 0 && this.selectedOrders.map(v => {
                        if (this.orderColDatasMap[v]) {
                            orderColKeys += this.orderColDatasMap[v].id + '|' + this.orderColDatasMap[v].ordertype + ",";
                        }
                    });
                    API.doSaveMobileCenterConfig({ ...this.baseParams, ...params, ...formValue, type: "contentSetting", orderColKeys: orderColKeys }).then(data => {
                        if (data.flag === "success") {
                            message.success(getLabel('83551', '保存成功！'));
                        } else {
                            message.error(getLabel('22620', "保存失败！"));
                        }
                        this.showDialog.contentSetting = false;
                        this.doInit();//刷新设置列表
                        this.resetSelectKeys = true;
                    });
                } else {
                    f.showErrors();
                }
            });
        }
    }

    /**
     *
     * @param {流程中心内容设置-删除tab}
     */
    @action
    doDelMobilecenterConfig = (params = {})  => {
        const that = this;
        Modal.confirm({
            title: getLabel(131329, '信息确认'),
            content: getLabel(33435, ' 确定要删除选中的记录吗？'),
            onOk() {
                API.doDelMobileCenterConfig({ ...that.baseParams, ...params }).then(data => {
                    if (data.flag === "success") {
                        message.success(getLabel('83472', '删除成功！'));
                    } else {
                        message.error(getLabel('83473', "删除失败！"));
                    }
                    that.resetSelectKeys = true;
                    that.doInit();//刷新设置列表
                });
            },
            onCancel() { },
            okText: getLabel(83446, '确定'),
            cancelText: getLabel(31129, '取消')
        })
    }

    /**
     * {流程中心内容设置-初始化form}
     */
    @action
    getMobileCenterConfig = (params)  => {
        API.getMobileCenterConfig({ ...this.baseParams, ...params }).then(data => {
            //API.getConfig({ ...this.baseParams, ...params }).then(data => {
            const { newflowFields = [], newflowValues, contentSettingFields = [], contentSettingValues, viewtypeFields = [], orderColDatas = [], selectedOrders = [] } = data;

            if(params.saveAs){//另存为直接置空tabid，重新走保存逻辑后刷新数据即可
                this.currentTabid = -1;
            }

            //流程中心内容设置
            if (params.type === "contentSetting") {
                this.selectedOrders = selectedOrders;
                this.orderColDatas = orderColDatas;
                this.orderColDatas.map(v => {
                    this.orderColDatasMap[v.id] = v;
                })
                this.viewtypeFields = viewtypeFields;
                this.contentSettingFields = contentSettingFields;
                this.contentSettingForm = new WeaForm();
                this.contentSettingForm.initFormFieldObj(contentSettingFields);
                //this.contentSettingForm.updateFields(contentSettingValues);
                this.wfContentLoading = false;
            }

            //新建流程操作菜单--流程来源
            if (params.type === "newflow") {
                this.newflowFields = newflowFields;
                this.newflowForm = new WeaForm();
                this.newflowForm.initFormFieldObj(newflowFields);
                this.newflowForm.updateFields(newflowValues);
            }
        });
    }

    /**
     * {设置流程中心内容设置的相关dialog}
     */
    @action
    setDialogShow = (name, value, params={}) =>  {
        if (name === 'newflow') {
            if (value === true) {
                this.getMobileCenterConfig({ type: "newflow" });
            }
        } else if (name === 'contentSetting') {
            if (value === true) {
                this.currentTabid = params.tabid;
                params.type = "contentSetting";
                this.getMobileCenterConfig(params);
            }
        }
        this.showDialog[name] = value;
    }

    setOperateDatas = (datas) => {
        this.operatedatas = datas;
        let _selectedOperate = { enable: [] };
        if (this.operatedatas) {
            this.operatedatas.map((data, i) => {
                if (data.enable == '1') {
                    _selectedOperate.enable.push(i);
                }
            });
        }
        this.selectedOperate = _selectedOperate;
    }

    setSelectedOperate = (datas) => {
        this.selectedOperate = datas;
    }

    setOrderColDatas = (datas) => {
        this.orderColDatas = datas;
        this.orderColDatas.map(v => {
            this.orderColDatasMap[v.id] = v;
        })
    }

    setSelectedOrders = (datas) => {
        if (datas) {
            this.selectedOrders = datas;
        }
    }
}